package org.cmg.study.spring.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cmg.study.spring.entity.FileDomain;
import org.cmg.study.spring.entity.MultiFileDomain;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * @author CMG
 * @version 1.0
 * @cLassName FileUploadController
 * @description
 * @date 2021/9/6 14:24
 **/
@Controller
public class FileUploadController {
    //的到一个用来记录日志的对象，这样在打印信息时能标记打印的是哪个类的信息
    private static final Log log = LogFactory.getLog(FileUploadController.class);

    @RequestMapping("/getFileUpload")
    public String getFileUpload() {
        return "fileUpload";
    }

    /**
     * 单文件上传
     * @param fileDomain
     * @param request
     * @return
     */
    @RequestMapping("/fileupload")
    public String oneFileUpload(@ModelAttribute FileDomain fileDomain, HttpServletRequest request) {
        /**
         * 文件上传到服务器的位置“/uploadfiles”，该位置是指
         * C:\\workspace\\Coding\\gitee\\spring-mvc-learn\\spring-mvc-fileupload\\target\\spring-mvc-fileupload-1.0\\uploadfiles
         * 发布后使用
         */
        String realPath = request.getServletContext().getRealPath("uploadfiles");
        String fileName = fileDomain.getFile().getOriginalFilename();
        File targetFile = new File(realPath, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        //上传
        try {
            fileDomain.getFile().transferTo(targetFile);
            log.info("成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "showFile";
    }

    @RequestMapping("/getmultiFile")
    public String getmultiFile() {
        return "multiFiles";
    }

    /**
     * 多文件上传
     */
    @RequestMapping("/multifile")
    public String multiFileUpload(@ModelAttribute MultiFileDomain multiFileDomain, HttpServletRequest request) {
        String realpath = request.getServletContext().getRealPath("uploadfiles");
        File targetDir = new File(realpath);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        List<MultipartFile> files = multiFileDomain.getFile();
        System.out.println("files"+files);
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            String fileName = file.getOriginalFilename();
            File targetFile = new File(realpath, fileName);
            // 上传
            try {
                file.transferTo(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "showMulti";
    }
}
